#include "script/glue/LuaGlue.h"
#include "script/glue/lua/Common.h"
#include "Timer.h"

#include "core/Value.h"
#include "boost/function.hpp"

namespace LuaGlue
{
	int Timer::create(lua_State *L)
	{
		luaL_error(L, "This type is unconstructable");
		return 1;
	}

	int Timer::getTime(lua_State *L)
	{
		lua_pushnumber(L, ::Timer::getInstance()->getTime());
		return 1;
	}

	//!TODO: cleanup the ref after execution
	int Timer::delay(lua_State *L)
	{
//		if(!lua_isfunction(L, -1)) return 0;
		int f = luaL_ref(L, LUA_REGISTRYINDEX);
		if(f == LUA_REFNIL) return 0;
		
		/*unsigned*/ long time = luaL_checklong (L, 1);
		lua_pop(L, 1);	
		::Timer::getInstance()->delay(boost::bind(do_lua_func0, f), time);
//		luaL_unref(L, LUA_REGISTRYINDEX, f);
		return 1;
	}
	
}

DECLARE(Timer)
META(Timer)
METHODS(Timer)
method(LuaGlue::Timer, getTime),
method(LuaGlue::Timer, delay),
END
